<template>
  <div class="blog-layout">
    <div id="vanta-background" class="vanta-container"></div>
    
    <!-- 全局加载组件 -->
    <div v-if="globalLoading" class="global-loading-overlay">
      <div class="loading-content">
        <div class="loading-spinner"></div>
        <div class="loading-text">加载中...</div>
      </div>
    </div>
    
    <main class="blog-main">
      <router-view />
    </main>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, onUnmounted, nextTick, ref, provide } from 'vue';
  import * as THREE from 'three';
  import NET from 'vanta/dist/vanta.net.min';

  defineOptions({
    name: 'BlogLayout',
  });

  let vantaEffect: any = null;
  const globalLoading = ref(true);

  // 提供全局加载状态给子组件
  const setGlobalLoading = (loading: boolean) => {
    globalLoading.value = loading;
  };

  provide('setGlobalLoading', setGlobalLoading);
  provide('globalLoading', globalLoading);

  // 预加载VANTA效果
  const preloadVanta = () => {
    // 在组件创建时就开始预加载
    try {
      if (typeof window !== 'undefined') {
        // 预创建Three.js场景
        const scene = new THREE.Scene();
        const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        const renderer = new THREE.WebGLRenderer({ alpha: true });

        // 预热WebGL上下文
        renderer.setSize(1, 1);
        document.body.appendChild(renderer.domElement);
        renderer.domElement.style.position = 'absolute';
        renderer.domElement.style.top = '-9999px';
        renderer.domElement.style.left = '-9999px';

        // 渲染一帧以预热
        renderer.render(scene, camera);

        // 清理预热元素
        document.body.removeChild(renderer.domElement);
      }
    } catch (error) {
      console.warn('预加载失败:', error);
    }
  };

  // 初始化vanta.js背景
  const initVantaBackground = () => {
    try {
      if (typeof window !== 'undefined') {
        console.log('Initializing VANTA.NET effect...');
        vantaEffect = NET({
          el: '#vanta-background',
          THREE: THREE,
          mouseControls: true,
          touchControls: true,
          gyroControls: false,
          minHeight: 200,
          minWidth: 200,
          scale: 1,
          scaleMobile: 1,
          color: 0x667eea,
          backgroundColor: 0x0a0a0a,
          points: 20, // 增加点数以覆盖更多区域
          maxDistance: 35, // 增加最大距离
          spacing: 25, // 增加间距
          showLines: true,
          size: 1.5,
          opacity: 0.8,
          animationSpeed: 0.3,
          // 添加更多配置以确保覆盖整个屏幕
          forceAnimate: true,
          // 确保点分布在更大的区域
          pointLimit: 30,
        });
        console.log('VANTA.NET effect initialized successfully');
        
        // 背景初始化完成后隐藏加载
        setTimeout(() => {
          globalLoading.value = false;
        }, 1000);
      }
    } catch (error) {
      console.warn('⚠️ Vanta.js 背景初始化失败:', error);
      useFallbackBackground();
      // 即使背景失败也要隐藏加载
      setTimeout(() => {
        globalLoading.value = false;
      }, 500);
    }
  };

  const useFallbackBackground = () => {
    const container = document.querySelector('.vanta-container');
    if (container) {
      container.classList.add('fallback-bg');
      console.log('Using fallback background');
    }
  };

  // 立即开始预加载
  preloadVanta();

  onMounted(async () => {
    // 使用nextTick确保DOM更新完成，然后立即初始化
    await nextTick();
    initVantaBackground();
  });

  onUnmounted(() => {
    if (vantaEffect) {
      vantaEffect.destroy();
    }
  });
</script>

<style scoped>
  .blog-layout {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    position: relative;
    overflow: hidden;
    background: #0a0a0a;
  }

  .vanta-container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
    background: #0a0a0a;
  }

  /* 备用背景 */
  .vanta-container.fallback-bg {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
  }

  .blog-main {
    flex: 1;
    max-width: 1200px;
    margin: 0 auto;
    padding: 2rem;
    width: 100%;
    position: relative;
    z-index: 1;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .blog-main {
      padding: 1rem;
    }
  }

  /* 全局加载样式 */
  .global-loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(10, 10, 10, 0.4);
    backdrop-filter: blur(3px);
    z-index: 9999;
    display: flex;
    align-items: center;
    justify-content: center;
    animation: fadeIn 0.3s ease;
  }

  .loading-content {
    text-align: center;
    color: white;
  }

  .loading-spinner {
    width: 60px;
    height: 60px;
    border: 3px solid rgba(255, 255, 255, 0.2);
    border-top: 3px solid #667eea;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin: 0 auto 1rem auto;
  }

  .loading-text {
    font-size: 1.1rem;
    font-weight: 500;
    color: rgba(255, 255, 255, 0.9);
    text-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  }

  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }

  @keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
  }
</style>
